<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/15
 * Time: 13:01
 */

namespace backend\modules\manager\models;

use common\models\Business;
use Yii;
use yii\base\Model;

class BusinessForm extends Model{
    /** 商家Id*/
    public $id;
    /** 商家名称 */
    public $name;
    /** 联系方式 */
    public $phone;
    /** logo图标路径 */
    public $logo;
    /** 商家类型 1影楼 2工作室 */
    public $type;
    /** 省份 */
    public $province;
    /** 市 */
    public $city;
    /** 区 */
    public $area;
    /** 详细地址 */
    public $address;
    /** 地图坐标 */
    public $location;
    /** 营业执照 */
    public $licence;
    /** 密码 */
    public $password;

    private $_business = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /** 必须 */
            [['id', 'name', 'phone', 'logo', 'type', 'province', 'city', 'area', 'address', 'location', 'licence'], 'required'],
            /** 校验信息 */
            ['id', 'validateId'],

            [['name', 'logo', 'address', 'licence', 'code_url'], 'string', 'max' => 200],
            [['phone', 'share_num', 'read_num'], 'string', 'max' => 11],
        ];
    }

    /**
     * 认证信息
     */
    public function validateId($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (!$this->getBusiness()) {
                $this->addError($attribute, 'Incorrect Id.');
            }
        }
    }

    public function getBusiness()
    {
        if($this->_business === false){
            $this->_business = Business::findIdentity($this->id);
        }
        return $this->_business;
    }

    /**
     * Add Business
     */
    public function add()
    {
        /** 验证 */
        if($this->validate()){
            $business = $this->getBusiness();
            $business->name = $this->name;
            $business->phone = $this->phone;
            $business->logo = $this->logo;
            $business->type = $this->type;
            $business->province = $this->province;
            $business->city = $this->city;
            $business->area = $this->area;
            $business->address = $this->address;
            $business->location = $this->location;
            $business->licence = $this->licence;
            /** 入库 */
            return $business->save(false);
        }
        return false;
    }
}